//
//  STDiskManager.swift
//  StarTimesON
//
//  Created by Toj on 2/22/23.
//  Copyright © 2023 StarTimes. All rights reserved.
//

import Foundation

// MARK: - 缓存Key
private let PersistenceKey = "Persistence"
public struct STDiskCacheKey {
    public var rawValue: String
    public init(rawValue: String) {
        self.rawValue = rawValue
    }
    
    fileprivate var obfuscated: String {
        return rawValue + PersistenceKey
    }
}

open class STDiskManager: NSObject {
    
    public static let manager = STDiskManager()
    
    private override init() { }
}

public extension STDiskManager {
    
    func setCache(key: STDiskCacheKey, value: String) {
        UserDefaults.standard.set(value, forKey: key.obfuscated)
        UserDefaults.standard.synchronize()
    }
    
    func setCache(key: STDiskCacheKey, value: Bool) {
        UserDefaults.standard.set(value, forKey: key.obfuscated)
        UserDefaults.standard.synchronize()
    }
    
    func setCache(key: STDiskCacheKey, value: Int) {
        UserDefaults.standard.set(value, forKey: key.obfuscated)
        UserDefaults.standard.synchronize()
    }
    
    func setCache(key: STDiskCacheKey, value: Double) {
        UserDefaults.standard.set(value, forKey: key.obfuscated)
        UserDefaults.standard.synchronize()
    }
    
    func setCache(key: STDiskCacheKey, value: Float) {
        UserDefaults.standard.set(value, forKey: key.obfuscated)
        UserDefaults.standard.synchronize()
    }
}

public extension STDiskManager {
    
    func cache(key: STDiskCacheKey) -> String {
        let cacheValue = UserDefaults.standard.string(forKey: key.obfuscated) ?? ""
        return cacheValue
    }
    
    func cacheString(key: STDiskCacheKey) -> String {
        return cache(key: key)
    }
    
    func cacheBool(key: STDiskCacheKey) -> Bool {
        let cacheValue = UserDefaults.standard.bool(forKey: key.obfuscated)
        return cacheValue
    }
    
    func cacheInt(key: STDiskCacheKey) -> Int {
        let cacheValue = UserDefaults.standard.integer(forKey: key.obfuscated)
        return cacheValue
    }
    
    func cacheDouble(key: STDiskCacheKey) -> Double {
        let cacheValue = UserDefaults.standard.double(forKey: key.obfuscated)
        return cacheValue
    }
    
    func cacheFloat(key: STDiskCacheKey) -> Float {
        let cacheValue = UserDefaults.standard.float(forKey: key.obfuscated)
        return cacheValue
    }
}
